//
//  UITextFieldUtil.swift
//  Extend
//
//  Created by shufang zou on 2018/1/17.
//  Copyright © 2018年 敬信. All rights reserved.
//

import Foundation

public typealias OnClearTextClick = () -> ();

var clearClickMap: Dictionary<NSInteger, OnClearTextClick> = {
    return Dictionary<NSInteger, OnClearTextClick>()
}()

var clearTag = 0

public extension UITextField {
    
    /// 给uitextfield添加一个清除按钮
    func setModifyClearButton(_ click: @escaping OnClearTextClick) {
        let clearButton = UIButton(type: .custom)
        clearButton.setImage(UIImage(named: "clear_textField"), for: .normal)
        clearButton.frame = CGRect(x: 0, y: 0, width: 28, height: 28)
        clearButton.contentMode = .scaleAspectFit
        clearButton.addTarget(self, action: #selector(UITextField.clear(sender:)), for: .touchUpInside)
        clearTag += 1;
        clearButton.tag = clearTag
        clearClickMap.updateValue(click, forKey: clearTag);
        self.rightView = clearButton
        self.rightViewMode = .whileEditing
    }

    /// 点击清除按钮，清空内容
    @objc func clear(sender: UIButton) {
        self.text = ""
        clearClickMap[sender.tag]!();
    }
}
